import { useRuntimeConfig } from "nuxt/app";
const req_interceptors = []; //请求拦截方法存放
const res_interceptors = []; //响应拦截方法存放

const basePathMap = {
  test: 'http://test.center.xiongmaodangao.com/',
  prod: 'http://center.xiongmaodangao.com/',
}
let basePath = basePathMap['test']
if (process.client) {
  if (process.dev) {
    const runtimeConfig = useRuntimeConfig()
    basePath = basePathMap[runtimeConfig.public.apiEnv || 'test']
  } else {
    basePath = window.location.origin
  }
}

/**
 * demo
 * request(url, {
      method: 'POST', // *GET, POST, PUT, DELETE, etc.
      mode: 'cors', // no-cors, *cors, same-origin
      cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
      credentials: 'same-origin', // include, *same-origin, omit
      headers: {
        'Content-Type': 'application/json'
        // 'Content-Type': 'application/x-www-form-urlencoded',
      },
      redirect: 'follow', // manual, *follow, error
      referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
      body: JSON.stringify(data) // body data type must match "Content-Type" header
    })
  }

  view more
  https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
 */

/**
 * @param url 
 * @param option 
 * @returns 
 */
const request = (url, option = {} as any) => {
  if (!option.method) {
    option.method = "GET";
  }
  //多个请求拦截器依次更改option
  req_interceptors.forEach((fn) => (option = fn(option)));
  return new Promise((resolve, reject) => {
    //使用$fetch
    $fetch(basePath + url, option)
      .then((res) => {
        //多个响应拦截器依次更改res
        res_interceptors.forEach((fn) => (res = fn(res)));

        resolve(res);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

request.interceptors = {
  request: {
    use: (fn) => {
      req_interceptors.push(fn);
      return fn;
    },
    eject: (data) => {
      if (req_interceptors.indexOf(data) !== -1) {
        req_interceptors.splice(req_interceptors.indexOf(data), 1);
      }
    },
  },
  response: {
    use: (fn) => {
      res_interceptors.push(fn);
      return fn;
    },
  },
  eject: (data) => {
    if (res_interceptors.indexOf(data) !== -1) {
      res_interceptors.splice(res_interceptors.indexOf(data), 1);
    }
  },
};

export default request;
